package com.kits.store.ui

import android.content.ContentValues
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.core.content.FileProvider
import com.kits.store.R
import com.kits.store.db.FileBean
import com.kits.store.db.FileBeanHelper
import kotlinx.android.synthetic.main.fragment_file_provider.*
import me.yokeyword.fragmentation.ISupportFragment
import me.yokeyword.fragmentation.SupportFragment
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.*


/**
 * 通过FileProvider访问
 */
class FileProviderFragment : SupportFragment(){
    private var currentPhotoPath:String? = null
    private var photoFileUri:Uri? = null
    companion object{
        /**
         * 保存到应用外部存储空间的沙盒文件夹，在沙盒文件夹中的文件不会通知MediaStore去扫描
         */
        const val SAVE_TO_APP_EXTERNAL = 1000
        /**
         * 保存到公共目录
         */
        const val SAVE_TO_PUBLIC= 2000
        fun newInstance() :FileProviderFragment{

            val args = Bundle()
            val fragment = FileProviderFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_file_provider,container,false)
    }

    override fun onResume() {
        super.onResume()
        initView()
    }

    private fun initView(){
        btnSystemCamera.setOnClickListener {
            val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            if (takePictureIntent.resolveActivity(requireContext().packageManager) != null){
                val filename: String = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.CHINA).format(Date()).toString() + ".png"
                // 这个是访问应用在外部存储空间中创建的文件
                val file =  File(requireContext().getExternalFilesDir(Environment.DIRECTORY_DCIM), filename)
                //val file =  File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), filename)
                currentPhotoPath = file.absolutePath
                println("currentPhotoPath == $currentPhotoPath")
                val fileUri: Uri = FileProvider.getUriForFile(requireContext(), "com.kits.store.fileProvider", file)
                println("fileUri == $fileUri")
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri)
                startActivityForResult(takePictureIntent, SAVE_TO_APP_EXTERNAL)
            }
        }

        btnPublicFileCamera.setOnClickListener {
            val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            if (takePictureIntent.resolveActivity(requireContext().packageManager) != null){

               // val fileUri: Uri = FileProvider.getUriForFile(requireContext(), "com.kits.store.fileProvider", file)
                photoFileUri = getUriByMediaStore()
                println("fileUri == $photoFileUri")
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoFileUri)
                startActivityForResult(takePictureIntent, SAVE_TO_PUBLIC)
            }
        }

        btnCreateFile.setOnClickListener {
            val filename: String = SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(Date()).toString() + ".txt"
            // 这个是访问应用在外部存储空间中创建的文件
            val file =  File(requireContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), filename)
            val outputStream = FileOutputStream(file)
            outputStream.write("写下一段文字用于测试\n".toByteArray())
            outputStream.close()
        }
        btnShareFile.setOnClickListener {
            send2OtherApp(File(requireContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), "20201111113300.txt"))
        }

        btnInsert.setOnClickListener {
            val filename: String = SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(Date()).toString() + ".txt"
            // 这个是访问应用在外部存储空间中创建的文件
            val file =  File(requireContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), filename)
            val outputStream = FileOutputStream(file)
            outputStream.write("写下一段文字用于测试 ${filename}\n".toByteArray())
            outputStream.close()

            val fileBean = FileBean()
            fileBean.dir = Environment.DIRECTORY_DOCUMENTS
            fileBean.fileName = filename
            fileBean.uri = FileProvider.getUriForFile(requireContext(), "com.kits.store.fileProvider", file).toString()
            FileBeanHelper.getInstance().insert(fileBean)

        }

        btnQueryAll.setOnClickListener {
            FileBeanHelper.getInstance().queryAll()
        }

        btnPaths.setOnClickListener {
            val rootPath = Environment.getRootDirectory().absolutePath
            println("rooPath == $rootPath")

            val filesPath = requireContext().filesDir.absolutePath
            println("fileDirPath == $filesPath")

            val cachePath = requireContext().cacheDir.absolutePath
            println("cacheFilePath == $cachePath")

            val externalPath= Environment.getExternalStorageDirectory().absolutePath
            println("externalDirPath == $externalPath")

            val externalFilesPath = requireContext().getExternalFilesDir(Environment.DIRECTORY_MUSIC)
            println("externalFilesPath == $externalFilesPath")

            val externalCachePath = requireContext().externalCacheDir?.absolutePath
            println("externalCachePath == $externalCachePath")

            requireContext().externalMediaDirs.forEach {
                println("externalMediaPath == ${it.absolutePath}")
            }

        }
    }

    /**
     * 通过MediaStore获取到Uri
     */

    fun getUriByMediaStore():Uri?{
        val contentValues = ContentValues()
        val filename: String = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.CHINA).format(Date()).toString() + ".png"
        contentValues.put(MediaStore.Images.Media.DESCRIPTION, "This is an image")
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, filename)
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/png")
        return context?.contentResolver?.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        println("requestCode == $requestCode;resultCode == $resultCode")
        if (resultCode == RESULT_OK){
            when(requestCode){
                SAVE_TO_APP_EXTERNAL-> {
                    // 这是Android7.0的写法
                    ivShowPhoto.setImageBitmap(BitmapFactory.decodeFile(currentPhotoPath))
                    return
                }
                SAVE_TO_PUBLIC ->{
                    // 获取失败
//                    val fileUri = data?.data
//                    println("fileUri == $fileUri")
                    val inputStream = context?.contentResolver?.openInputStream(photoFileUri!!)
                    ivShowPhoto.setImageBitmap(BitmapFactory.decodeStream(inputStream))
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data)

    }

    @RequiresApi(Build.VERSION_CODES.Q)
    private fun installApk():Uri?{
        // 通过MediaStore获取到Apk的uri
        val queryCursor = context?.contentResolver?.query(MediaStore.Downloads.EXTERNAL_CONTENT_URI,null,
            MediaStore.Images.Media.DISPLAY_NAME+"=?", arrayOf("test.apk"),null)
        return queryCursor?.let {
            val queryUri:Uri? = null
            if (it.count == 0){
                return@let queryUri
            }else{

                return@let queryUri
            }
        }

    }

    private fun send2OtherApp(shareFile:File){
        if (shareFile.exists()){
            val share = Intent(Intent.ACTION_SEND).apply {
                val fileUri = FileProvider.getUriForFile(requireContext(),"com.kits.store.fileProvider",shareFile)
                println("fileUri == $fileUri")
                putExtra(Intent.EXTRA_STREAM,fileUri)
                // 添加读的权限
                //addFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION)
                //addFlags( Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                addFlags( Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)
                type = "text/plain"
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            println("flags == ${share.flags}")
            startActivity(Intent.createChooser(share, "分享文件"))
        }
    }

}